package com.qsl.rabbit.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author: 青石路
 */
@Slf4j
public class TaskMessageListener implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) {
        String content = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("消费者接收到消息：{}", content);
        handleTask(content);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("消息确认失败，异常：", e);
        }
    }

    /**
     * 业务处理
     * @param message 消息内容
     * @author: 青石路
     */
    private void handleTask(String message) {
        try {
            // 业务处理
            log.info("处理任务：{}", message);
            int i = 3 / (message.length() % 10);
            if (i == 1) {
                throw new OutOfMemoryError("模拟内存溢出");
            }
            log.info("任务处理结果：{}", i);
        } catch (Exception | Error e) {
            log.error("处理任务失败，异常：", e);
        }
    }
}
